__author__ = 'Robin'
#coding:utf-8
from django.http import HttpRequest
from django.http import HttpResponse
from django.template import Context, loader, RequestContext
from django.template.loader import get_template
from django.shortcuts import render, get_object_or_404, render_to_response, HttpResponseRedirect
from django import http
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from datiandouweb.models import UserProfile,UserCertificate,Certificate
from datiandouweb.forms import UserProfileForm
import datetime
import json
import logging
import os
from django.utils import timezone
from django.http import HttpResponse, HttpResponseBadRequest
from django.conf import settings
from django.db import transaction
from django.template.response import TemplateResponse
from datiandouweb import fwsutils




####################################personal center#################################
@csrf_exempt
def load_personal_edit(request):
    userEmail = request.session.get("userEmail")
    userID = request.session.get('userID')
    stateMessage = request.session.get('stateMessage')
    userEmail = 'luobintianya@yahoo.com.cn'
    request.session["userEmail"]=userEmail;
    request.session["userID"]=5;

    enLevel = Certificate.objects.filter(Ref_id=1,Certificate_type=1) #英语1  语言类
    jpLevel = Certificate.objects.filter(Ref_id=2,Certificate_type=1) #日语2  语言类
    try:
        profile = UserProfile.objects.get(pk=userID)
    except UserProfile.DoesNotExist:
        profile = UserProfile()
        print str(userEmail)+" isn't in the database yet."
    else:
        print str(userEmail)+ "is in the database."
    print(profile.User_work_type)

    try:
        enCertificate = UserCertificate.objects.filter(Certificate_id__Ref_id =1,Certificate_id__Certificate_type=1).get(User_id=profile)
    except UserCertificate.DoesNotExist :
        enCertificate = UserCertificate()
    try:
        jpCertificate = UserCertificate.objects.filter(Certificate_id__Ref_id =2,Certificate_id__Certificate_type=1).get(User_id=profile)
    except UserCertificate.DoesNotExist:
        jpCertificate = UserCertificate()
        print(enCertificate)

    if('stateMessage' in request.session):
        del request.session['stateMessage']
    #return TemplateResponse(request,'personalcenter/personal_info.html',{'profile': profile,'enLevel':enLevel,
    #                                                                    'jpLevel':jpLevel,
    #                                                                    'enCertificate':enCertificate,
    #                                                                  'jpCertificate':jpCertificate,
    #                                                                 'stateMessage':stateMessage})
    return fwsutils.fws_response('personalcenter/personal_info.html', request,{'profile': profile,'enLevel':enLevel,
                                                                                          'jpLevel':jpLevel,
                                                                                          'enCertificate':enCertificate,
                                                                                           'jpCertificate':jpCertificate,
                                                                                           'stateMessage':stateMessage})





@transaction.autocommit
@csrf_exempt
def save_persional_info(request):
    print('-------start-------')
    stateMessage = ""
    userID = request.POST.get("userID")
    userEmail = request.POST.get("userEmail")
    userName = request.POST.get("userName")
    cellPhone = request.POST.get("cellPhone")
    introduce = request.POST.get("introduce")
    workType = (request.POST.getlist("workType"))
    Update_time= timezone.datetime.now()
    jpLevel = request.POST.get("jpLevel").strip()
    enLevel = request.POST.get("enLevel").strip()
    print(jpLevel)
    print(enLevel)
    if(workType != None and len(workType)>=2):
        workType = 3
    else:
        workType = workType[0].strip()
    print(workType)
    try:
        userInfo = UserProfile.objects.get(pk=userID)
        userInfoForm = UserProfileForm(instance=userInfo,data={'User_id':userID,'User_name':userName,
                                                               'User_cellphone':cellPhone,'User_email':userEmail,
                                                               'User_introduce':introduce,'Update_time':Update_time,
                                                               'User_work_type':workType})
    except UserProfile.DoesNotExist:
        userInfoForm = UserProfileForm(data=request.POST)
    except Exception,e:
        stateMessage ="不存在此人信息"
        logging.info(e)

    try:
        enLevel = Certificate.objects.get(pk=enLevel)
        enCertificate=UserCertificate.objects.filter(Certificate_id__Ref_id =1,Certificate_id__Certificate_type=1).get(User_id=userInfo)  #1 英语类别
        enCertificate.Certificate_id=enLevel
    except UserCertificate.DoesNotExist:
        enCertificate = UserCertificate.objects.create(User_id = userInfo,Certificate_id=enLevel,Create_time= timezone.datetime.today(),Update_time= timezone.datetime.today())

    try:
        jpLevel = Certificate.objects.get(pk=jpLevel)
        jpCertificate=UserCertificate.objects.filter(Certificate_id__Ref_id =2,Certificate_id__Certificate_type=1).get(User_id=userInfo) #2 日语类别
        jpCertificate.Certificate_id=jpLevel
    except UserCertificate.DoesNotExist:
        jpCertificate = UserCertificate.objects.create(User_id = userInfo,Certificate_id=jpLevel,Create_time= timezone.datetime.today(),Update_time= timezone.datetime.today())

    try:
        print(userInfoForm.is_valid())
        if userInfoForm.is_valid() and enCertificate and jpCertificate:
            userInfoForm.save()
            enCertificate.save()
            jpCertificate.save()
            stateMessage="个人信息更新成功!"
            transaction.commit()
        else:
            stateMessage="个人信息更新失败!"
        print(userInfoForm.errors)
    except Exception, e:
        transaction.rollback()
        stateMessage="个人信息更新失败!"
        print(e)
    print(stateMessage)
    request.session['stateMessage'] = stateMessage
    return fwsutils.fws_redirect_response('load', request,{'stateMessage': stateMessage})

